const cloud = require('wx-server-sdk');
const moment = require('moment');
const _ = require('lodash');

cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV
});
const db = cloud.database({ env: cloud.DYNAMIC_CURRENT_ENV });

/**
 * 新增打卡
 * @param {*} event 
 * @param {*} context 
 */
exports.main = async (event, context) => {
  // 获取基础数据
  const wxContext = cloud.getWXContext();
  // 待实现：校验当前用户所在组织和打卡的组织是否一致
  const params = event.params;
  params.group_name = params.daka_poi.group_name;
  params.openid = wxContext.OPENID;
  params.day_time = moment().format('YYYY-MM-DD');
  params.createdAt = moment().format('YYYY-MM-DD HH:mm:ss');
  params.created_at = moment().valueOf();
  if (params.type === 'SIGN_OUT') { // 签退打卡，计算本轮时长
    // 1. 获取当前用户在当日和当前组织的签到打卡记录 - SIGN_IN
    const where_params = {
      openid: params.openid,
      group_name: params.group_name,
      day_time: params.day_time,
      type: 'SIGN_IN',
    };
    const record_res = await db.collection('daka_records').where(where_params).orderBy('createdAt', 'desc').limit(1).get();
    const record = record_res.data[0] || null;
    if (!!record) {
      params.duration = params.created_at - record.created_at;
    }
  }
  try {
    await db.collection('daka_records').add({ data: params });
    return {code: 0, msg: 'OK' };
  } catch (error) {
    throw {code: -1, msg: error.message };
  }
};